package com.xfc.web.controller.school;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xfc.common.annotation.Log;
import com.xfc.common.constant.Constants;
import com.xfc.common.core.controller.BaseController;
import com.xfc.common.core.domain.AjaxResult;
import com.xfc.common.core.page.TableDataInfo;
import com.xfc.common.enums.BusinessType;
import com.xfc.common.utils.SecurityUtils;
import com.xfc.common.utils.poi.ExcelUtil;
import com.xfc.message.NoticeMessage;
import com.xfc.school.domain.*;
import com.xfc.school.service.*;
import com.xfc.system.service.ISysRoleService;
import com.xfc.system.service.ISysUserService;
import com.xfc.wx.domain.ScWxUser;
import com.xfc.wx.service.IScWxUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 课程日期Controller
 * 
 * @author wtf
 * @date 2021-12-26
 */
@Slf4j
@RestController
@RequestMapping("/school/schedule")
public class ScCourseScheduleController extends BaseController
{
    @Autowired
    private IScCourseScheduleService scCourseScheduleService;
    @Autowired
    private IScCourseService courseService;
    @Autowired
    private IScTeacherService scTeacherService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private IScBuyCourseService scBuyCourseService;
    @Autowired
    private IScMarketingCourseService scMarketingCourseService;
    @Autowired
    private IScClassEvaluationFormService scClassEvaluationFormService;

    @Autowired
    private NoticeMessage message;

    @Autowired
    private IScBuyCourseService buyCourseService;

    @Autowired
    private IScWxUserService wxUserService;

    @Autowired
    private IScStudentService studentService;
    /**
     * 查询课程日期列表
     */
    @PreAuthorize("@ss.hasPermi('school:schedule:list')")
    @GetMapping("/list")
    public TableDataInfo list(String startTime, String courseNumber) throws Exception {

        QueryWrapper<ScCourseSchedule> queryWrapper=new QueryWrapper<>();
        queryWrapper.apply(Objects.nonNull(startTime),
                "date_format (start_time,'%Y-%m-%d') = date_format('" +startTime+ "','%Y-%m-%d')");
        if(Objects.nonNull(courseNumber)){
            queryWrapper.eq("course_number",courseNumber);
        }
        //查询用户角色
        String roleCode=sysRoleService.getUerRole(String.valueOf(SecurityUtils.getUserId()));
        if (!Objects.equals("admin",SecurityUtils.getUsername())){
            //判断用户是否是管理员
            if (!Objects.equals(Constants.USER_ROLE,roleCode)){
                ScTeacher scTeacher=scTeacherService.getOne(new QueryWrapper<ScTeacher>().eq("teacher_number",SecurityUtils.getUsername()));
                if (Objects.isNull(scTeacher)){
                   throw new Exception("没有查询到教师信息");
                }
                queryWrapper.eq("teacher_number", scTeacher.getId());
                queryWrapper.le("start_time",new Date());
            }
        }
        queryWrapper.orderByDesc("start_time");
        startPage();
        List<ScCourseSchedule> list = scCourseScheduleService.list(queryWrapper);
        //查询课程信息
        list.forEach(l->{
            //查询课程名称
            if (Objects.nonNull(l.getCourseNumber())){
                ScCourse scClass=courseService.getById(l.getCourseNumber());
                if (Objects.nonNull(scClass)){
                    //课程名称
                    l.setCourseName(scClass.getClassName());
                }
            }
            //教师姓名
            ScTeacher teacher=scTeacherService.getById(l.getTeacherNumber());
            if (Objects.nonNull(teacher)){
                l.setTeacherName(teacher.getTeacherName());
            }
        });
        return getDataTable(list);
    }

    /**
     * 导出课程日期列表
     */
    @PreAuthorize("@ss.hasPermi('school:schedule:export')")
    @Log(title = "课程日期", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export()
    {
        List<ScCourseSchedule> list = scCourseScheduleService.list();
        ExcelUtil<ScCourseSchedule> util = new ExcelUtil<>(ScCourseSchedule.class);
        return util.exportExcel(list, "schedule");
    }

    /**
     * 获取课程日期详细信息
     */
    @PreAuthorize("@ss.hasPermi('school:schedule:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        ScCourseSchedule courseSchedule = scCourseScheduleService.getById(id);

        if (Objects.nonNull(courseSchedule)) {
            ScCourse scClass = courseService.getById(courseSchedule.getCourseNumber());
            if (Objects.nonNull(scClass)) {
                //课程名称
                courseSchedule.setCourseName(scClass.getClassName());
            }
            if (Objects.nonNull(courseSchedule)) {
                ScTeacher scTeacher =scTeacherService.getById(courseSchedule.getTeacherNumber());
                if (Objects.nonNull(scTeacher)) {
                    courseSchedule.setTeacherId(scTeacher.getTeacherName());
                }
            }
        }
            return AjaxResult.success(courseSchedule);

    }

    /**
     * 获取课程日期详细信息
     */
    @GetMapping(value = "/details")
    public TableDataInfo queryDetails(String id,ScBuyCourse scBuyCourse)
    {

        QueryWrapper<ScCourseSchedule> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",id);
        startPage();
        List<ScCourseSchedule> list = scCourseScheduleService.list(queryWrapper);

        //查询课程信息
        list.forEach(l->{
            //查询课程名称
            if (Objects.nonNull(l.getCourseNumber())){
                ScCourse scClass=courseService.getById(l.getCourseNumber());
                if (Objects.nonNull(scClass)){
                    //课程名称
                    l.setCourseNumber(scClass.getClassName());
                }
            }
            //教师姓名
            ScTeacher teacher=scTeacherService.getById(l.getTeacherNumber());
            if (Objects.nonNull(teacher)){
                l.setTeacherNumber(teacher.getTeacherName());
            }
            //查询上课的总人数
            QueryWrapper<ScBuyCourse> queryWrapper1=new QueryWrapper<>();
            queryWrapper1.apply(
                    "date_format (start_time,'%Y-%m-%d') <= date_format('" +scBuyCourse.getCourseStartime()+ "','%Y-%m-%d')");
            queryWrapper1.apply(
                    "date_format (end_time,'%Y-%m-%d') >= date_format('" +scBuyCourse.getCounrseEndtime()+ "','%Y-%m-%d')");
            queryWrapper1.eq("class_id",scBuyCourse.getClassId());
            List<ScBuyCourse> listbuycourse = scBuyCourseService.list(queryWrapper1);
            l.setTotalStudentNum(String.valueOf(listbuycourse.size()));

            //查询销课的人数
            QueryWrapper<ScMarketingCourse> queryWrapper2=new QueryWrapper<>();
            queryWrapper2.eq("course_startime",scBuyCourse.getCourseStartime());
            queryWrapper2.eq("counrse_endtime",scBuyCourse.getCounrseEndtime());
            queryWrapper2.eq("course_id",scBuyCourse.getClassId());
            List<ScMarketingCourse> listMarketing = scMarketingCourseService.list(queryWrapper2);
            l.setMarketingStudentNum(String.valueOf(listMarketing.size()));

            //查询课堂评价的总人数
            QueryWrapper<ScClassEvaluationForm> queryWrapper3=new QueryWrapper<>();
            queryWrapper3.eq("start_time",scBuyCourse.getCourseStartime());
            queryWrapper3.eq("end_time",scBuyCourse.getCounrseEndtime());
            queryWrapper3.eq("course_number",scBuyCourse.getClassId());
            List<ScClassEvaluationForm> listEvaluation = scClassEvaluationFormService.list(queryWrapper3);
            l.setEvaluationStudentNum(String.valueOf(listEvaluation.size()));

        });

        return getDataTable(list);
    }

    /**
     * 新增课程日期
     */
    @PreAuthorize("@ss.hasPermi('school:schedule:add')")
    @Log(title = "课程日期", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ScCourseSchedule scCourseSchedule)
    {
        return toAjax(scCourseScheduleService.save(scCourseSchedule));
    }

    /**
     * 修改课程日期
     */
    @PreAuthorize("@ss.hasPermi('school:schedule:edit')")
    @Log(title = "课程日期", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ScCourseSchedule courseSchedule) {
        ScCourseSchedule courseSchedule1=scCourseScheduleService.getById(courseSchedule.getId());
        if (scCourseScheduleService.updateById(courseSchedule)) {
            //查询课程信息
            if (Objects.nonNull(courseSchedule)) {
                //查询学生信息
                QueryWrapper<ScBuyCourse> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("class_id", courseSchedule.getCourseNumber());
                queryWrapper.gt("class_surplus_time", 0);
                List<ScBuyCourse> buyCoursesList = buyCourseService.list(queryWrapper);
                List<Map<String,String>> openIdList = new ArrayList<>();
                buyCoursesList.forEach(j -> {
                    Map<String,String> map=new HashMap<>(2);
                    //查询学生信息
                    ScStudent student = studentService.getById(j.getStudentId());
                    if (Objects.nonNull(student)) {
                        ScWxUser user = wxUserService.getOne(new QueryWrapper<ScWxUser>().eq("mobile", student.getStudentMobile()));
                        if (Objects.nonNull(user)&& StringUtils.isNotEmpty(user.getOpenId())&& StringUtils.isNotEmpty(student.getParentName())) {
                            //查询openid
                            map.put("openId", user.getOpenId());
                            map.put("name", student.getParentName());
                            openIdList.add(map);
                        }
                    }
                });
                if (openIdList.size() > 0) {

                    //发送通知
                    message.CourseChanage(openIdList, courseSchedule.getCourseName(), DateUtil.format(courseSchedule1.getStartTime(), "yyyy-MM-dd HH:mm:ss")+"~"+DateUtil.format(courseSchedule1.getEndTime(), "yyyy-MM-dd HH:mm:ss")
                            ,DateUtil.format(courseSchedule.getStartTime(), "yyyy-MM-dd HH:mm:ss")+"~"+DateUtil.format(courseSchedule.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
                } else {
                    log.error("通知发送失败");
                }

            }
        }
        return AjaxResult.success();
    }

    /**
     * 删除课程日期
     */
    @PreAuthorize("@ss.hasPermi('school:schedule:remove')")
    @Log(title = "课程日期", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids){
		List<String> list=new ArrayList<>();
    	if (ids!=null&&ids.length>0) {
            for (String id : ids) {
                list.add(id);
            }
		}
    	if (scCourseScheduleService.removeByIds(list)){
            //根据课程查询购买的课程
            list.forEach(l->{
                //查询课程信息
                ScCourseSchedule courseSchedule=scCourseScheduleService.getById(l);
                if (Objects.nonNull(courseSchedule)){
                    //查询学生信息
                    QueryWrapper<ScBuyCourse> queryWrapper=new QueryWrapper<>();
                    queryWrapper.eq("class_id",courseSchedule.getCourseNumber());
                    queryWrapper.gt("class_surplus_time",0);
                    List<ScBuyCourse> buyCoursesList=buyCourseService.list(queryWrapper);
                    List<String> openIdList=new ArrayList<>();
                    buyCoursesList.forEach(j->{
                        //查询学生信息
                        ScStudent student=studentService.getById(j.getStudentId());
                        if (Objects.nonNull(student)){
                            ScWxUser user=wxUserService.getOne(new QueryWrapper<ScWxUser>().eq("mobile",student.getStudentMobile()));
                            //查询openid
                            openIdList.add(user.getOpenId());
                        }
                    });
                    if (openIdList.size()>0){
                        //发送通知
                        message.courseCanel(openIdList,courseSchedule.getCourseName(), DateUtil.format(courseSchedule.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
                    }else {
                        log.error("通知发送失败");
                    }

                }
            });
        }
        return AjaxResult.success();
    }
}
